﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HQPad.Extensions;
using HQPad.Models;
using HQPad.Services;
using HQPad.DAL;
using HQPad.Helpers;

namespace HQPad.Controllers
{
    public class BattleboardController : BaseController
    {
        //
        // GET: /Battleboard/
        [HttpPost]
        public ActionResult Generate(string name, FormCollection form)
        {
            /*
             * Get the character by name.
             */
            IUnitOfWork context = new CharacterContext();
            IUnitOfWork hqContext = new HQContext();
            ICharacterService characterService = new CharacterService(context);

            string userName = AuthenticationHelper.GetCurrentUserName(HttpContext);
            string sessionId = AuthenticationHelper.GetCurrentSessionId(Request);

            // Get character by slug, user and session.
            ScratchPad character = characterService.GetScratchPadCharacter(userName, sessionId, name);

            if (character == null)
                return RedirectToAction("NotFound", "Character");

            string fileName = string.Format("{0}battleboard.pdf", name);

            /*
             * Get the selected battleboard type.
             */
            string boardType = !string.IsNullOrEmpty(form["boardType"]) ? form["boardType"] : "Standard";
            int powerInTalisman = !string.IsNullOrEmpty(form["powerInTalisman"]) ? int.Parse(form["powerInTalisman"]) : 0;

            /*
             * Get battleboard model data.
             */
            CharacterRulesHelper helper = new CharacterRulesHelper(hqContext, character.Xml);
            BattleboardModel model = helper.CreateBattleboardModel();
            model.TalismanPower = powerInTalisman;

            /*
             * Generate the battlebaord pdf.
             */
            byte[] contents = null;

            // create helper.
            BattleboardHelper bbHelper = new BattleboardHelper(model);

            // generate pdf and return bytes.
            contents = bbHelper.GenerateBattleboard(boardType);

            /*
             * Set http response.
             */
                Response.AddHeader("Content-Disposition", string.Format("inline; {0}", fileName));

            return File(contents, "application/pdf");
        }

    }
}
